package fun.diaoer.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

public class StringUtil extends StringUtils {

	/**
	 * 下划线字符
	 */
	public static final char UNDERLINE = '_';
	
	public static String nullToEmpty(String string) {
	    return (string == null) ? "" : string;
	}

	/**
	 * 比较（忽略空格、大小写）
	 * 
	 */
	public static boolean equalsTrimIgnoreCase(String string1, String string2) {
		return equalsIgnoreCase(trim(string1), trim(string2));
	}

	/**
	 * 比较（忽略空格）
	 * 
	 */
	public static boolean equalsTrim(String string1, String string2) {
		return equals(trim(string1), trim(string2));
	}

	/**
	 * 比较（忽略空格、NULL与空字符串）
	 * 
	 */
	public static boolean equalsTrim(String string1, String string2, boolean nullAsEmpty) {
		if (nullAsEmpty) {
			if (string1 == null)
				string1 = "";
			if (string2 == null)
				string2 = "";
		}
		return equals(trim(string1), trim(string2));
	}

	/**
	 * 函数功能说明 ： 获得文件名的后缀名. 修改者名字： 修改日期： 修改内容：
	 * 
	 * @参数： @param fileName @参数： @return @return String @throws
	 */
	public static String getExt(String fileName) {
		if (contains(fileName, "."))
			return fileName.substring(fileName.lastIndexOf(".") + 1);
		else
			return "";
	}

	/**
	 * 字符串下划线转驼峰格式
	 *
	 * @param param
	 *            需要转换的字符串
	 * @return 转换好的字符串
	 */
	public static String underlineToCamel(String param) {
		if (isEmpty(param)) {
			return EMPTY;
		}
		String temp = param.toLowerCase();
		int len = temp.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char c = temp.charAt(i);
			if (c == UNDERLINE) {
				if (++i < len) {
					sb.append(Character.toUpperCase(temp.charAt(i)));
				}
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}

	/**
	 * 字符串驼峰转下划线格式
	 *
	 * @param param
	 *            需要转换的字符串
	 * @return 转换好的字符串
	 */
	public static String camelToUnderline(String param) {
		if (isEmpty(param)) {
			return EMPTY;
		}
		int len = param.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char c = param.charAt(i);
			if (Character.isUpperCase(c) && i > 0) {
				sb.append(UNDERLINE);
			}
			sb.append(Character.toLowerCase(c));
		}
		return sb.toString();
	}

	/**
	 * 拼接某属性的 get方法
	 * 
	 * @param fieldName
	 * @return String
	 */
	public static String parGetName(String fieldName) {
		if (isBlank(fieldName)) {
			return null;
		}
		return "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
	}

	/**
	 * 拼接在某属性的 set方法
	 * 
	 * @param fieldName
	 * @return String
	 */
	public static String parSetName(String fieldName) {
		if (isBlank(fieldName)) {
			return null;
		}
		return "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
	}

	/**
	 * 
	 * 全角字符->半角字符转换 只处理全角的空格，全角！到全角～之间的字符，忽略其他
	 */
	static final char SBC_CHAR_START = 65281;// 全角！
	static final char SBC_CHAR_END = 65374;// 全角～
	static final int CONVERT_STEP = 65248;// 全角半角转换间隔
	static final char SBC_SPACE = 12288;// 全角空格
	static final char DBC_SPACE = ' ';// 半角空格
	static final char SBC_STOP = 12289;// 全角顿号
	static final char DBC_STOP = ',';// 半角顿号
	static final char CNH_DBL_QUAT = 8220;// 中文双引号
	static final char DBC_DBL_QUAT = 34;// 半角双引号
	static final char CNH_QUAT = 8216;// 中文引号
	static final char DBC_QUAT = 39;// 半角引号

	public static String toDbc(String src) {
		if (StringUtil.isBlank(src)) {
			return src;
		}

		StringBuilder buf = new StringBuilder(src.length());
		char[] ca = src.toCharArray();
		for (int i = 0; i < src.length(); i++) {
			if ((int) ca[i] >= SBC_CHAR_START && ca[i] <= SBC_CHAR_END) { // 如果位于全角！到全角～区间内
				buf.append((char) (ca[i] - CONVERT_STEP));
			} else if (ca[i] == SBC_SPACE) { // 如果是全角空格
				buf.append(DBC_SPACE);
			} else if (ca[i] == SBC_STOP) { // 如果是全角顿号
				buf.append(DBC_STOP);
			} else if (ca[i] == CNH_DBL_QUAT || ca[i] == CNH_DBL_QUAT + 1) { // 如果是中文双引号
				buf.append(DBC_DBL_QUAT);
			} else if (ca[i] == CNH_QUAT || ca[i] == CNH_QUAT + 1) { // 如果是中文引号
				buf.append(DBC_QUAT);
			} else { // 不处理全角空格，全角！到全角～区间外的字符
				buf.append(ca[i]);
			}
		}
		return buf.toString();
	}

	/**
	 * 字符前添加0
	 */
	public static String dataFormatZeroByLength(String data, int totalLength) {
		String afterData = data;
		if (data.length() < totalLength) {
			do {
				afterData = "0" + afterData;
			} while (afterData.length() < totalLength);
		}
		return afterData;
	}

	/**
	 * 将集合按属性名转化为以分隔符分隔的字符串
	 * 
	 * @param list
	 * @param property
	 * @param splitSymbol
	 * @return
	 */
	public static String toStringFromList(Collection<?> list, String property, String splitSymbol) {
		if (list != null) {
			List<String> stringList = new ArrayList<String>(list.size());
			for (Object obj : list) {
				stringList.add((String) BeanUtil.getProperty(obj, property));
			}
			return toStringFromStrArray(stringList.toArray(new String[stringList.size()]), splitSymbol);
		} else
			return null;
	}

	public static String toStringFromStrList(Collection<String> list, String splitSymbol) {
		if (list != null)
			return toStringFromStrArray(list.toArray(new String[list.size()]), splitSymbol);
		else
			return "";
	}

	/**
	 * 将STRING数组转化为以分隔符分隔的字符串
	 * 
	 * @param array
	 * @param splitSymbol
	 * @return
	 */
	public static String toStringFromStrArray(String[] array, String splitSymbol) {
		StringBuffer sb = new StringBuffer();
		if (array != null) {
			for (String s : array) {
				if (sb.length() > 0)
					sb.append(splitSymbol);
				sb.append(s);
			}
			return sb.toString();
		} else
			return null;
	}

	public static String toStringFromStrArray(String[] array) {
		return toStringFromStrArray(array, ";");
	}

	/**
	 * String截位，不怕异常
	 */
	public static String substring(String str, int length) {
		if (StringUtil.isBlank(str))
			return str;

		if (str.length() > length)
			str = str.substring(0, length);

		return str;
	}

	/**
	 * 按每行最大长度将字符串分行
	 * 
	 * @param str
	 * @param length
	 * @return
	 */
	public static String splitLineByMaxLineLength(String str, int length) {
		if (StringUtil.isBlank(str) || length <= 0)
			return str;

		String lineSplit = "\n";
		StringBuffer newStr = new StringBuffer();

		String fullText = str.replaceAll("\\r", "");
		String[] lines = fullText.split("\\n");
		for (int lineIndex = 0; lineIndex < lines.length; lineIndex++) {
			String lineText = lines[lineIndex];
			if (lineText.length() <= length) {
				newStr.append(lineText);
				if (lineIndex < (lines.length - 1))
					newStr.append("\\n");
				continue;
			}
			while (lineText.length() > length) {
				String word = lineText.substring(length, length + 1);
				if (isChineseOrSpace(word)) {
					newStr.append(lineText.substring(0, length));
					newStr.append(lineSplit);
					lineText = lineText.substring(length);
				} else {
					int blankIndex = getLastChineseOrSpaceOfCurrentLine(lineText, length);
					if (blankIndex >= 0) {
						newStr.append(lineText.substring(0, blankIndex + 1));
						newStr.append(lineSplit);
						lineText = lineText.substring(blankIndex + 1);
					} else {
						newStr.append(lineText.substring(0, length));
						newStr.append(lineSplit);
						lineText = lineText.substring(length);
					}
				}
			}
			newStr.append(lineText);
			if (lineIndex < (lines.length - 1))
				newStr.append(lineSplit);
		}
		int lastSplitIndex = fullText.lastIndexOf("\n");
		while (lastSplitIndex >= 0 && lastSplitIndex == (fullText.length() - 1)) {
			newStr.append(lineSplit);

			fullText = fullText.substring(0, lastSplitIndex);
			lastSplitIndex = fullText.lastIndexOf("\n");
		}
		return newStr.toString();
	}

	private static int getLastChineseOrSpaceOfCurrentLine(String text, int endIndex) {
		String s = text.substring(0, endIndex);
		for (int i = s.length() - 1; i >= 0; i--) {
			char item = s.charAt(i);
			if (isChineseOrSpace(String.valueOf(item)))
				return i;
		}
		return -1;
	}

	private static boolean isChineseOrSpace(String text) {
		// 是否空格
		if (StringUtil.isBlank(text))
			return true;

		// 是否中文
		Pattern pattern = Pattern.compile("^[\u4e00-\u9fa5]+$");
		Matcher matcher = pattern.matcher(text);
		return matcher.matches();
	}

}
